import { useEffect, useState, Fragment, useCallback } from 'react'
import { NavLink, useNavigate } from 'react-router-dom'
import { Table, Button, Space, Tooltip, Modal, message } from 'antd'
import {
  DeleteOutlined,
  FormOutlined,
  CloudUploadOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import { http } from '@/utils/http'
const { confirm } = Modal;

export default function NewsDraft() {
  const navigate = useNavigate()
  const [draftList, setDraftList] = useState([])  // 存放草稿箱文章
  const [category, setCategory] = useState([])  // 文章分类列表

  const { username } = JSON.parse(window.sessionStorage.getItem('news'))

  // 获取草稿箱文章列表
  const getDraftList = useCallback(async () => {
    const { data } = await http.get(`/news?author=${username}&auditState=0`)
    setDraftList(data)
  }, [username])

  // 获取文章分类列表
  const getCategoryList = async () => {
    const { data } = await http.get('/categories')
    setCategory(data)
  }

  // 输入文章分类id找到对应的文章分类名
  const findCategoryName = id => {
    return category?.find(item => item.id === id)?.title
  }

  useEffect(() => {
    getDraftList()
    getCategoryList()
  }, [getDraftList])

  // 删除文章的回调
  const onClickDelete = item => {
    console.log(item)
    confirm({
      title: '您将从草稿箱中移除此文章',
      icon: <ExclamationCircleOutlined />,
      content: '该操作确定后不可撤销！！',
      onOk() {
        return new Promise((resolve, reject) => {
          deleteOk(resolve, reject, item)
        })
      },
      onCancel() {
        message.info('您取消了该操作！', 2)
      },
    });
  }

  const deleteOk = (resolve, _, item) => {
    http.delete(`/news/${item.id}`)
      .then(() => {
        resolve()
        setDraftList(draftList.filter(data => data.id !== item.id))
        message.success('删除文章成功！', 2)
      })
      .catch(() => {
        message.error('删除文章失败！', 2)
        setTimeout(() => {
          resolve()
          navigate(0)
        }, 1000)
      })
  }

  // 提交审核的回调
  const onClickPublish = item => {
    http.patch(`/news/${item.id}`, {
      auditState: 1
    })
      .then(() => {
        navigate('/audit-manage/list')
        message.success('提交审核成功！', 2)
      })
      .catch(() => {
        message.error('提交审核失败！', 2)
      })
  }

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      render: id => <b>{id}</b>
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      align: 'center',
      width: '500px',
      ellipsis: true,
      render: (title, { id }) => {
        return <NavLink to={`/news-manage/preview/${id}`} >{title}</NavLink>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
      align: 'center',
    },
    {
      title: '新闻分类',
      align: 'center',
      dataIndex: 'categoryId',
      render: categoryId => findCategoryName(categoryId)
    },
    {
      title: '操作',
      align: 'center',
      render: item => {
        return (
          <Space>
            <Tooltip title="delete">
              <Button danger type="primary" shape="circle" icon={<DeleteOutlined />}
                onClick={() => onClickDelete(item)} />
            </Tooltip>
            <Tooltip title="edit">
              <Button type="primary" shape="circle" icon={<FormOutlined />}
                onClick={() => navigate(`/news-manage/update/${item.id}`)} />
            </Tooltip>
            <Tooltip title="publish">
              <Button type="primary" shape="circle" icon={<CloudUploadOutlined />}
                onClick={() => onClickPublish(item)} />
            </Tooltip>
          </Space>
        )
      }
    }
  ];

  return (
    <Fragment>
      <Table
        dataSource={draftList}
        columns={columns}
        rowKey={item => item.id}
        pagination={{
          pageSize: 5
        }}
      />
    </Fragment>
  )
}